#pragma once

#include <iostream>
#include "protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

class ServerCal
{

public:
    ServerCal()
    {
    }

    Response CalulaterHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
        {
            if (req.y == 0)
                resp.code = Div_Zero;
            else
                resp.result = req.x / req.y;
        }
        break;
        case '%':
        {
            if (req.y == 0)
                resp.code = Mod_Zero;
            else
                resp.result = req.x % req.y;
        }
        break;
        default:
            resp.code = Other_Oper;
            break;
        }
        return resp;
    }
    // package = "len"\n"10 + 20"\n"
    std::string Calculator(std::string &package)
    {
        std::string content;
        // 对发来的报文进行解析，提取出有效载荷
        bool r = Decode(package, content);
        if (!r) return "";
        //"10 + 20"

        // 在对有效载荷进行反序列化处理-转化为结构型数据
        Request req;
        r = req.Desrialize(content);
        if (!r)
            return "";
        // "10 + 20" --> x = 10, op = +, y = 20

        // 处理数据
        content = "";
        Response resp = CalulaterHelper(req);
        // result = 30, code = 0
        // 序列化
        resp.Serialize(content);
        // "30 0"

        // 封装报头
        //  std::string package;
        content = Encode(content);
        // "len"\n"30 0"\n"

        return content;
    }
    ~ServerCal()
    {
    }
};
